package com.example.financialsystem;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.financialsystem.adapter.FlowsAdapter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import models.FlowStatistic;
import models.Record;
import models.StatisticInfo;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import others.ServerResponse;
import utils.OkhttpUtil;

import static others.Const.IP;
import static others.Const.PORT;
import static others.Const.currentBook;
import static others.Tools.ToastShow;
import static utils.GsonUtil.String2ListFlowsServerResponse;
import static utils.GsonUtil.String2ListStatisticServerResponse;

public class RecordListActivity extends AppCompatActivity implements View.OnClickListener {

    @BindView(R.id.details_title)
    TextView textTitle;
    @BindView(R.id.details_surplus)
    TextView textSurplus;
    @BindView(R.id.details_income)
    TextView textIncome;
    @BindView(R.id.details_outcome)
    TextView textOutcome;
    @BindView(R.id.book_background_layout)
    LinearLayout background;
    @BindView(R.id.details_recyclerView)
    RecyclerView detailsRecyclerView;

    private Calendar today = Calendar.getInstance();
    private int year = today.get(Calendar.YEAR);
    private int month = today.get(Calendar.MONTH);
    private int day = today.get(Calendar.DATE);
    private List<FlowStatistic> flowList = new ArrayList<>();

    private int timeZoneType;
    private String responseDate;
    public static final int UPDATE_LIST = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_home);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        timeZoneType = intent.getIntExtra("timeZoneType", 0);
        StatisticInfo statistic = (StatisticInfo) intent.getSerializableExtra("statistic");
        double income = statistic.getIncome();
        double outcome = statistic.getOutcome();

        textTitle.setOnClickListener(this);
        textTitle.setText(setBackTitle(timeZoneType));

        textSurplus.setText(income - outcome + "");
        textIncome.setText(income + "");
        textOutcome.setText(outcome + "");

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        detailsRecyclerView.setLayoutManager(layoutManager);
//        FlowsAdapter adapter = new FlowsAdapter(flowList);
//        detailsRecyclerView.setAdapter(adapter);

        getDataFromServer();
    }

    public String setBackTitle(int timeZoneType) {
        String title = "<";
        switch (timeZoneType) {
            case 0:
                title += "今天" + month + "月" + day + "日";
                break;
            case 1:
                title += "本周";
                break;
            case 2:
                title += year + "年" + month + "月";
                break;
            case 3:
                title += year + "年";
                break;
            default:
                break;
        }
        return title + "流水";
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.details_title:
                finish();
                break;
        }
    }

//    public void simulate() {
//        StatisticInfo statisticInfo = new StatisticInfo("2020-04-13", 2, 0+"", 200, 1000);
//        List<Record> records = new ArrayList<>();
//        Date date = new Date();
//        Record record1 = new Record(null,"65853611f6644021b5f412071e050b92","0cd7966e5d664f92a15d0408c62b0df8",
//                0,0,2000.0,"早午晚餐","午餐","现金","现金","中南海请朋友吃饭",null,date,date);
//        Record record2 = new Record(null,"65853611f6644021b5f412071e050b92","0cd7966e5d664f92a15d0408c62b0df8",
//                1,0,5000.0,"早午晚餐","午餐","现金","现金","中南海请朋友吃饭",null,date,date);
//        records.add(record1);
//        records.add(record2);
//        FlowStatistic flowStatistic = new FlowStatistic(statisticInfo, records);
//        flowList.add(flowStatistic);
//        StatisticInfo statisticInfo1 = new StatisticInfo("2020-04-06", 2, 1+"", 300, 50);
//        FlowStatistic classification_record1 = new FlowStatistic(statisticInfo1, null);
//        flowList.add(classification_record1);
//    }

    public void getDataFromServer(){
        String url = "http://" + IP + ":" + PORT + "/portal/flowStatistics.do";
        RequestBody requestBody = new FormBody.Builder()
                .add("bookId",currentBook.getId())
                .add("timeZoneType",timeZoneType+"")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Response response = client.newCall(request).execute();
                    responseDate = response.body().string();
                    Message message = new Message();
                    message.what = UPDATE_LIST;
                    handler.sendMessage(message);
                }catch (Exception e){
                    e.printStackTrace();
                    Looper.prepare();
                    ToastShow("我们好像遇到了一些问题1(RecordListActivity)");
                    Looper.loop();
                }
            }
        }).start();
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case UPDATE_LIST:
                    try {
                        ServerResponse<List<FlowStatistic>> serverResponse = String2ListFlowsServerResponse(responseDate);
                        if (serverResponse.getStatus() == 0){
                            flowList = serverResponse.getData();
                            FlowsAdapter adapter = new FlowsAdapter(flowList);
                            detailsRecyclerView.setAdapter(adapter);
                        }else {
                            ToastShow("我们好像遇到了一些问题2(RecordListActivity)");
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        ToastShow("抱歉，可能出了一些意外3(RecordListActivity)");
                    }
                    break;
                default:
                    break;
            }
        }
    };

}


